package com.yzk.train.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yzk.train.business.entity.Train;
import com.yzk.train.business.entity.TrainExample;
import com.yzk.train.business.mapper.TrainMapper;
import com.yzk.train.business.request.TrainQueryReq;
import com.yzk.train.business.request.TrainSaveReq;
import com.yzk.train.business.response.TrainQueryResp;
import com.yzk.train.common.exception.BusinessException;
import com.yzk.train.common.exception.ExceptionEnum;
import com.yzk.train.common.response.PageResp;
import com.yzk.train.common.utils.SnowUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TrainService {

    @Resource
    private TrainMapper trainMapper;

    /**
     * 保存 / 更新 车次
     * @param req
     */
    public String save(TrainSaveReq req) {
        Train train = BeanUtil.copyProperties(req, Train.class);
        DateTime now = DateTime.now();
        train.setUpdateTime(now);
        if (ObjectUtil.isNull(train.getId())) {

            // 保存之前，先校验唯一键是否存在，车次编号
            Train trainDB = selectByUnique(req.getCode());
            if (ObjectUtil.isNotEmpty(trainDB)) {
                throw new BusinessException(ExceptionEnum.BUSINESS_TRAIN_CODE_UNIQUE_ERROR);
            }

            train.setId(SnowUtil.getSnowflakeNextId());
            train.setCreateTime(now);
            trainMapper.insert(train);
            return "保存成功";
        } else {
            trainMapper.updateByPrimaryKeySelective(train);
            return "编辑成功";
        }
    }

    /**
     * 查询车次列表（分页）
     * @param req
     */
    public PageResp<TrainQueryResp> queryList(TrainQueryReq req) {
        TrainExample trainExample = new TrainExample();
        trainExample.setOrderByClause("code desc");
        // 如果有车次编号，则按照车次编码查询
        if (StrUtil.isNotBlank(req.getTrainCode())) {
            trainExample.createCriteria().andCodeLike("%" + req.getTrainCode() + "%");
        }
        // 使用分页插件
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        List<Train> trains = trainMapper.selectByExample(trainExample);
        // 使用 PageInfo 包装查询结果
        PageInfo<Train> pageInfo = new PageInfo<>(trains);
        // 转换为 PageResp
        List<TrainQueryResp> list = BeanUtil.copyToList(trains, TrainQueryResp.class);
        return new PageResp<>(pageInfo.getTotal(), list);
    }

    /**
     * 查询车次列表 （无分页）
     */
    public List<TrainQueryResp> queryAll() {
        TrainExample trainExample = new TrainExample();
        trainExample.setOrderByClause("code asc");
        List<Train> trains = trainMapper.selectByExample(trainExample);
        return BeanUtil.copyToList(trains, TrainQueryResp.class);
    }

    /**
     * 查询车次列表 （无分页）
     */
    public List<Train> queryAllNotResp() {
        TrainExample trainExample = new TrainExample();
        trainExample.setOrderByClause("code asc");
        return trainMapper.selectByExample(trainExample);
    }

    /**
     * 根据ID删除车次
     * @param id
     */
    public void delete(Long id) {
        trainMapper.deleteByPrimaryKey(id);
    }

    /**
     * 校验唯一键
     *
     * @param code 车次编号
     * @return
     */
    private Train selectByUnique(String code) {
        TrainExample trainExample = new TrainExample();
        trainExample.createCriteria()
                .andCodeEqualTo(code);
        List<Train> list = trainMapper.selectByExample(trainExample);
        if (CollUtil.isNotEmpty(list)) {
            return list.get(0);
        } else {
            return null;
        }
    }
}
